package com.lgj.resource;

import com.lgj.core.OauthResourceAuthenticationEntryPoint;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;

/**
 * 资源服务配置
 * @author guangjie.liao
 * @date 2022/11/18 08:21
 */
@Slf4j
@Order(6)
@Configuration
@EnableResourceServer
public class OauthResourceConfig extends ResourceServerConfigurerAdapter {

    @Value("${spring.application.name}")
    private String serverName;

    @Autowired
    private RedisConnectionFactory redisConnectionFactory;

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        resources.resourceId(serverName);
        resources.tokenStore(tokenStore());
        resources.authenticationEntryPoint(new OauthResourceAuthenticationEntryPoint());
    }


    /**
     * token 存储器
     **/
    @Bean
    public TokenStore tokenStore() {
        return new RedisTokenStore(redisConnectionFactory);
    }


    @Override
    public void configure(HttpSecurity http) throws Exception {
        // 资源链路
        http
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
            .and().authorizeRequests().antMatchers("/oauth/**").permitAll()
            // 其他请求都需认证
            //.and().logout().logoutSuccessHandler(new ClientLogoutSuccessHandler())
            .and().authorizeRequests().anyRequest().authenticated()
            .and().cors();

        http.csrf().disable();
    }

}
